<template>
  <common-modal
    ref="modalRef"
    v-bind="attrs"
    title="添加媒体账户"
    @sure="search"
    @cancel="handleCancel"
    @before-close="reset"
    @open="handleOpen"
  >
    <el-form
      label-width="130px"
      :rules="rules"
      ref="formRef"
      :inline="false"
      :model="formData"
    >
      <el-form-item label="媒体名称：">
        <el-input
          v-model="account.mediaName"
          placeholder="请输入媒体名称"
          clearable
          disabled
        />
      </el-form-item>
      <el-form-item label="媒体账号：" prop="mediaAccount">
        <account-set ref="accountRef" v-model:mediaAccount="formData.mediaAccount" />
      </el-form-item>
    </el-form>
  </common-modal>
</template>
<script>
export default {
  inheritAttrs: false,
};
</script>
<script setup>
import { reactive, useAttrs, ref, onMounted } from "vue";
import commonModal from "@/components/commonModal.vue";
import AccountSet from "./accountSet.vue";
import useForm from "@/hooks/useForm";
import { SearchAccountByMediaId } from "@/apis/media";
import { ElMessage } from "element-plus";
import { MediaAddAccount, MediaEditAccount } from "@/apis/media";
const props = defineProps({
  type: {
    type: String,
    default: "add",
  },
  account: {
    type: Object,
    default: () => ({}),
  },
});
const accountRef = ref(null)
const attrs = useAttrs();
const formData = reactive({
  mediaAccount: [],
});
const modalRef = ref(null);
// 确定
const handleSure = async () => {
  await Promise.all(createSavePromiseList())
  ElMessage.success({
    message: "操作成功",
    type: "success",
  });
  emits("success");
  handleCancel();
};
const { formRef, search, reset } = useForm(handleSure);
const validateAccount = (rule, value, cb) => {
    accountRef.value?.validate().then(res => {
        cb()
    }).catch(err => cb(new Error(err)))
}
const rules = {
  name: [{ required: true, message: "请输入媒体名称" }],
  mediaAccount: [{ validator: validateAccount, message: "请输入完善媒体账号信息" }],
};

// 取消 关闭弹窗
const handleCancel = () => {
  modalRef.value?.close();
};

// 确定
const emits = defineEmits(["success"]);

// 打开弹窗
const handleOpen = () => {
  const { account } = props;
  SearchAccountByMediaId(account.id).then((res) => {
    console.log("res: ", res);
    formData.mediaAccount = res || [];
  });
};

const createSavePromiseList = () => {
    return (formData.mediaAccount || []).map(v => {
        v.mediaId = props.account.id
        if (v.id) return MediaEditAccount(v)
        return MediaAddAccount(v)
    })
}
</script>
